//获取应用实例
var app = getApp();

var FormCheckRule = {
	idCardRule1: /^[0-9]{14}([0-9]|X|x)$/,
	idCardRule2: /^[0-9]{17}([0-9]|X|x)$/,
	nameRule: /^[^ ]{2,60}$/,
	telRule: /^[1]{1}[0-9]{10}$/,
	carNbrSufRule: /^[a-zA-Z]{1}[a-zA-Z0-9]{4}[a-zA-Z0-9\u4E00-\u9FA5]{1,2}$/,

	cardNbrNullMessage:"请输入受理编号！",
	cardNbrErrorMessage:"请输入正确的受理编号！",
	cardErrorMessage:"请扫描正确的受理编号！",
	cardPlateNullMessage:"请输入车牌号码！",
	cardPlateErrorMessage:"请输入正确的车牌号码！",
	urgentApplicantNullMessage:"请输入车主名称！",
	urgentApplicantErrorMessage:"请输入正确的申请人姓名！",
	contactNameNullMessage:"请输入收件人姓名！",
	contactNameErrorMessage:"请输入正确的收件人姓名！",

	cellNumNullMessage:"请输入收件人电话！",
	cellNumErrorMessage:"请输入正确的收件人电话！",

	areaNameNullMessage:"请选择所在地区！",
	streetNullMessage:"请输入详细地址！",
	streetMinNullMessage:"详细地址不能小于5个字符！",
	checkService:"请阅读并同意《机动车牌邮寄服务协议》",
	typeSelection:"请选择车辆类型！"
};

Page({
	data: {
		showView: false, //车牌前缀
		showViewList: false, //车辆列表
		items:[
			{userId: 1, name: "京"}, {userId: 2, name: "津"}, {userId: 3, name: "沪"}, {userId: 4, name: "渝"}, {userId: 5, name: "湘"}, {userId: 6, name: "黑"}, {userId: 7, name: "琼"},
			{userId: 8, name: "贵"}, {userId: 9, name: "苏"}, {userId: 10, name: "闽"}, {userId: 11, name: "辽"}, {userId: 12, name: "宁"}, {userId: 13, name: "粤"}, {userId: 14, name: "陕"},
			{userId: 15, name: "豫"}, {userId: 16, name: "新"}, {userId: 17, name: "赣"}, {userId: 18, name: "冀"}, {userId: 19, name: "甘"}, {userId: 20, name: "鄂"}, {userId: 21, name: "吉"},
			{userId: 22, name: "浙"}, {userId: 23, name: "云"}, {userId: 24, name: "桂"}, {userId: 25, name: "皖"}, {userId: 26, name: "晋"}, {userId: 27, name: "鲁"}, {userId: 28, name: "川"},
			{userId: 29, name: "蒙"}, {userId: 30, name: "藏"}, {userId:31, name: "青"}
		],
		list:[
			{code: "01", value: "大型汽车"}, {code: "02", value: "小型汽车"}, {code: "03", value: "使馆汽车"}, {code: "04", value: "领馆汽车"}, {code: "05", value: "境外汽车"}, {code: "06", value: "外籍汽车"},
			{code: "07", value: "普通摩托车"}, {code: "08", value: "轻便摩托车"}, {code: "09", value: "使馆摩托车"}, {code: "10", value: "领馆摩托车"}, {code: "11", value: "境外摩托车"}, {code: "12", value: "外籍摩托车"}, {code: "13", value: "低速车"}, {code: "14", value: "拖拉机"}, {code: "15", value: "挂车"}, {code: "16", value: "教练汽车"}, {code: "17", value: "教练摩托车"},
			{code: "18", value: "试验汽车"}, {code: "19", value: "试验摩托车"}, {code: "20", value: "临时入境汽车"}, {code: "21", value: "临时入境摩托车"}, {code: "22", value: "临时行驶车"}, {code: "23", value: "警用汽车"}, {code: "24", value: "警用摩托车"}
		],
    isCanScroll:true,
		userCellId: 0,
		cardNbrIconType: "",
		cardFixIconType: "",
		cardApplicant: "",
		recipientNameType: "",
		contactNumberType: "",

		//省，市，区选择
		area:"请选择所在地区",
		areaStyle:"color: #B2B2B2;font-size:34rpx",
		typeStyle:"color: #B2B2B2;font-size:34rpx",
		cardNbrStyle:"",
		isNoticeShow:false,  //服务协议说明
		needInvoice:0,  //是否勾选

		//输入框默认值
		cardNbr:"",   //受理编号
		userCellName: "粤",  //车牌前缀
		cardFix: "", //车牌号码
		recipientName: "", //收件人姓名
		typeSelectionText: "请选择车辆类型",
		isShowFootNav:true,
		num: 0
	},

	onLoad: function () {
		app.initAddress();
		var page =  app.getStorageSync(app.globalData.cacheData);
		var that = this;
        if(app.globalData.openId!=null&&app.globalData.openId!=''&&app.globalData.openId!="null"){
			var opt2 = {
				url: app.globalData.host+"/wx/cn/list.ajax",
				data: {
					'accountId':app.globalData.openId,
					'bizFlag':app.globalData.bizDoingFlag,
					'orderType':app.globalData.orderType
				},
				sucFn:function (result) {
					var num = "";
					if(result.body.orderList.length!=0){
						num = result.body.orderList.length;
					}
					that.setData({
						"num": num
					});
				}
			};
			app.ajax(opt2);
		}else {
			wx.login({//调用登录接口
				success: function (res) {
					var opt = {//后台兑换openId
						url: app.globalData.host + "/wx/cn/eo.ajax",
						data: {
							'code': res.code
						},
						sucFn: function (result) {
              if(result.body.openId!=null&&result.body.openId!=''&&result.body.openId!="null"){
                  app.globalData.openId = result.body.openId;
                  var opt2 = {
                      url: app.globalData.host+"/wx/cn/list.ajax",
                      data: {
                          'accountId':app.globalData.openId,
                          'bizFlag':app.globalData.bizDoingFlag,
                          'orderType':app.globalData.orderType
                      },
                      sucFn:function (result) {
                          var num = "";
                          if(result.body.orderList.length!=0){
                              num = result.body.orderList.length;
                          }
                          that.setData({
                              "num": num
                          });
                      }
                  };
                  app.ajax(opt2);
              }else{
                  app.toastAuthFailModal();
							}
						}
					};
					app.ajax(opt);
				}
			});
		}
		if(page){
			this.setData({
				cardNbr: page.cardNbr,
				userCellName: page.userCellName,
				typeSelectionText: page.typeSelectionText,
				typeSelectionCode: page.typeSelectionCode,
				applicant: page.applicant,
				cardFix: page.cardFix,
				recipientName: page.recipientName,
				contactNumber: page.contactNumber,
				area: page.area,
				"address.street": page.address?page.address.street:"",
				"needInvoice":page.needInvoice
			});

			if(page.address != null){
				this.setData({
					"area":page.area,
					//"areaStyle":"",
					"address.street":page.address.street,
					"address.provinceId":page.address.provinceId,
					"address.cityId":page.address.cityId,
					"address.countyId":page.address.countyId,
					"address.provinceName":page.address.provinceName,
					"address.cityName":page.address.cityName,
					"address.countyName":page.address.countyName,
					"address.cellNum":page.address.cellNum,
					"address.contactName":page.address.contactName
				});
			}
            if(page.area=='请选择所在地区'){
                this.setData({areaStyle: "color: #B2B2B2;font-size:34rpx"});
            }else{
                this.setData({areaStyle: "color:#1a1a1a;font-size:34rpx"});
            }
			// if(page.typeSelectionText){
			// 	if(page.typeSelectionText!="请选择车辆类型"){
			// 		this.setData({"typeStyle": ""});
			// 	}
			// }
		}
	},
	bindStop:function(event){

	},
	//分享功能
	onShareAppMessage:function () {
		return {
			title: '机动车牌邮寄服务',
			desc: '机动车牌邮寄服务!',
			path: '/pages/handle/handle'
		}
	},
	onHide:function () {
		app.setStorageSync(app.globalData.cacheData,this.data);
	},
	onShow:function () {
		var page = app.getStorageSync(app.globalData.cacheData);
		this.setData({
			num: page.num
		});
    },

	//底部切换页面方法
	toUrl:function (e) {
		var url = e.currentTarget.dataset.url;
		if(url!='/pages/handle/handle'){
            app.setStorageSync(app.globalData.cacheData,this.data);
			if(url == ''){
				var res = {
                    appid:app.globalData.appid,
                    path: app.globalData.path,
                    envVersion: app.globalData.envVersion
				}
				app.crossToUrl(res)
			}else {
				app.redirectTo({url: url});
			}
		}
	},

	//保存缓存
	saveCache:function(){
		app.setStorageSync(app.globalData.cacheData,this.data);
	},

	//确认提交按钮
  formSubmit:function(e){
		var formData = e.detail.value;
		var cardNbr = formData.cardNbr;
		var cardFix = formData.cardFix;
		var cardApplicant = formData.cardApplicant;
		var recipientName = formData.recipientName;
		var cardNumber = formData.cardNumber;
		var street = formData['address.street'];
		var provinceId = formData['address.provinceId'];
		var needInvoice = formData.needInvoice;
		var pageObj = this;
		var flag = app.check([
			{
				value: cardNbr,
				errorFocusName:"cardNbr",
        		errorScrollIntoViewName:"handleView",
				fn: function(value){
					if(value == ''){
						app.errorToast(FormCheckRule.cardNbrNullMessage);
						return false;
					}else if(value.length > 1){
						return true;
					}else {
						app.errorToast(FormCheckRule.cardNbrErrorMessage);
					}
				}
			},

			// {     //车牌号可以为空
			// 	value: cardFix,
			// 	rule: app.globalData.Rule.required,
			// 	errorFocusName:"cardFix",
			// 	message: FormCheckRule.cardPlateNullMessage
			// },
			// {
			// 	value: cardFix,
			// 	errorFocusName:"cardFix",
             //    errorScrollIntoViewName:"handleView",
			// 	fn: function (value) {
			// 		if(FormCheckRule.carNbrSufRule.test(value)){
			// 			return true;
			// 		}else if(value == ''){
			// 			return true;
			// 		}else {
			// 			app.errorToast(FormCheckRule.cardPlateErrorMessage);
			// 		}
			// 	}
			// },
			// {
			// 	value: this.data["typeSelectionText"],
             //    errorScrollIntoViewName:"handleView",
			// 	fn: function (value) {
			// 		if(value == '请选择车辆类型'){
			// 			app.errorToast(FormCheckRule.typeSelection);
			// 		}else {
			// 			return true;
			// 		}
			// 	}
			// },
			{
				value: cardApplicant,
				errorFocusName:"applicant",
        errorScrollIntoViewName:"handleView",
				fn: function (value) {
					if(value == ''){
						app.errorToast(FormCheckRule.urgentApplicantNullMessage);
					}else if(FormCheckRule.nameRule.test(value)){
						return true;
					}else {
						app.errorToast(FormCheckRule.urgentApplicantErrorMessage);
					}
				}
			}, {
				value: recipientName,
				errorFocusName:"recipientName",
        errorScrollIntoViewName:"cardApplicantView",
				fn: function (value) {
					if(value == ''){
						app.errorToast(FormCheckRule.contactNameNullMessage);
					}else if(FormCheckRule.nameRule.test(value)){
						return true;
					}else {
						app.errorToast(FormCheckRule.contactNameErrorMessage);
					}
				}
			}, {
				value: cardNumber,
				errorFocusName:"contactNumber",
        errorScrollIntoViewName:"recipientNameView",
				fn: function(value){
					if(value == ''){
						app.errorToast(FormCheckRule.cellNumNullMessage);
					}else if(FormCheckRule.telRule.test(value)){
						return true;
					}else {
						app.errorToast(FormCheckRule.cellNumErrorMessage);
					}
				}
			}, {
          value: provinceId,
          errorFocusName:"provinceId",
          errorScrollIntoViewName:"cardNumberView",
          rule: app.globalData.Rule.required,
          fn: function (value) {
              if(value!=''){
                  return true;
              }else{
                  app.errorToast(FormCheckRule.areaNameNullMessage);
                  return false
              }
          }
      }, {
				value: street,
				errorFocusName:"street",
                errorScrollIntoViewName:"areaView",
				fn: function(value){
					if(value ==''){
						app.errorToast(FormCheckRule.streetNullMessage);
					}else if(value.length<5) {
						app.errorToast(FormCheckRule.streetMinNullMessage);
					}else {
						return true;
					}
				}
			}
		]);

		if (!flag) {
			return false;
		}
		  if(needInvoice==0){
        app.errorToast(FormCheckRule.checkService);
			  return false;
		  }
      if(app.globalData.openId==''||app.globalData.openId==null||app.globalData.openId=="null"){
        app.toastAuthFailModal();
        return false;
      }
	  var postData = formData;
      var res = this.data;
      postData['address.fullAddr'] = formData['address.provinceName']+formData['address.cityName']+formData['address.countyName']+street;
      postData['carNbr'] = res.cardFix?res.userCellName+res.cardFix:'';
      postData['acceptNbr'] = res.cardNbr;
      postData['name'] = res.applicant;
      postData['address.cellNum'] = formData.cardNumber;
      postData['address.contactName'] = formData.recipientName;
	  var opt = {
		  url: app.globalData.host+"/wx/cn/handling.ajax",
		  data: postData,
		  sucFn:function (result) {
			  postData['serviceFee_cn'] = result.body.serviceFee;  //服务费
			  postData['totalChargeFee_cn'] = result.body.totalChargeFee; //总费用
			  postData['totalFee_cn'] = result.body.totalFee;
			  postData['isLocal'] = result.body.local;
			  postData['userCellName'] = res.userCellName;
			  postData['cardFix'] = res.cardFix;
			  app.setStorageSync(app.globalData.cacheOrderPay, postData);
			  app.navigateTo({url:'../payment/payment'})
		  }
	  };
	  app.ajax(opt);
	},

	//说明内容
	agreeTap:function (e) {
		this.setData({
			isNoticeShow:true,
			isShowFootNav: false
		});
	},
	//隐藏说明内容
	noticeKnowTap:function (e) {
		this.setData({
			isNoticeShow:false,
			isShowFootNav: true
		});
	},
	areaTap:function (e) {
		this.setData({
			isAddressShow: true,
			isShowFootNav: false
		});
	},

	//条形码
	bindViewTap: function() {
		var that = this;
		var path= /^[0-9a-zA-Z]*$/g;
		wx.scanCode({
				// onlyFromCamera: true,
			success: function(res){
				if(path.test(res.result)){
					that.setData({cardNbr: res.result });
				}else {
					app.errorToast(FormCheckRule.cardErrorMessage);
				}
			}
		})
	},
	//车牌前缀
	userListAction:function(e){
		this.setData({
			userCellName: e.target.dataset.name,
			showView: false,
			isShowFootNav: true
		})
	},

	//点击车牌前缀
	provinceName: function(e){
		this.setData({
			showView: true,
			isShowFootNav:false
		})
	},

	//输入框公用方法
	infoInput: function(e){
		var id = e.currentTarget.id,
	      value = e.detail.value.replace(/(^\s*)|(\s*$)/g,"");

		if(id == "cardNbr"){ //受理编号
			var pattern = /([^A-Za-z0-9]|\s)*/g,
				  that = this;
			setTimeout(function(){
				value = value.replace(pattern, '');
				that.setData({"cardNbr": value});
			},0);
			if(value==''){
                this.setData({acceptanceIconType: "success"});
			}else if(value.length==1){
				this.setData({acceptanceIconType: "error"});
			}else {
				this.setData({acceptanceIconType: "success"});
			}
		}else if(id == "applicant"){
			this.setData({applicant: value});
        if(value==''){
            this.setData({cardNameIconType: "success"});
        }else if(FormCheckRule.nameRule.test(value)){
				this.setData({cardNameIconType: "success"});
			} else if(value.length>0){
				this.setData({cardNameIconType: "error"});
			}else {
				this.setData({
					cardNameIconType: "",
					applicant: value
				});
			}
		}else if(id == "recipientName"){
			this.setData({recipientName: value});
      if(value==''){
        this.setData({recipientNameIconType: "success"});
      }else if (FormCheckRule.nameRule.test(value)) {
				this.setData({recipientNameIconType: "success"});
			} else if (value.length > 0) {
				this.setData({recipientNameIconType: "error"});
			}else {
				this.setData({recipientNameIconType: ""});
			}
		}else if(id == "contactNumber"){
			value = value.substr(0, 11);
			this.setData({contactNumber: value});
        if(value==''){
            this.setData({urgentLinkTelIconType: "success"});
        }else if (FormCheckRule.telRule.test(value)) {
			this.setData({urgentLinkTelIconType: "success"});
		} else if (value.length > 0) {
			this.setData({urgentLinkTelIconType: "error"});
		} else {
			this.setData({urgentLinkTelIconType: ""});
		}

		}else if(id == "address.street"){
			this.setData({"address.street": value});
      if(value==''){
          this.setData({streetNameIconType: "success"});
      }else if(value.length>4){
				this.setData({streetNameIconType: "success"});
			} else if(value.length>0){
				this.setData({streetNameIconType: "error"})
			}else {
				this.setData({streetNameIconType: ""})
			}
		}

	},

	//是否勾选
	checkTap:function (e) {
		var needInvoice = e.target.dataset.agree;
		if(needInvoice==0){
			needInvoice = 1;
		}else{
			needInvoice = 0;
		}
		this.setData({needInvoice: needInvoice});
	},
	//车牌号码只能输入大写
	infoProFix: function(e){
		var pattern = /([^A-Za-z0-9]|\s)*/g,
		    target = e.detail,
				that=this;
		if(target.value.length<=6){
			setTimeout(function(){
				that.setData({
					cardFix: target.value.replace(pattern, "").replace("I", 1).replace("O", 0).toUpperCase()
				});
			},0);
		}

		if(target.value.length<6&&target.value.length!=0){
			if(target.value.length==1){
				if(!isNaN(target.value)){
					that.setData({cardNbrIconType: "error"});
					return false;
				}else {
					that.setData({cardNbrIconType: "success"});
					return false;
				}
			}
			if(FormCheckRule.carNbrSufRule.test(target.value)){
				that.setData({cardNbrIconType: "success"});
				return false;
			}else {
				that.setData({cardNbrIconType: "error"});
				return false;
			}
		}else {
			if(!isNaN(target.value)&&target.value!=''){
				that.setData({cardNbrIconType: "error"});
			}else {
				that.setData({cardNbrIconType: "success"});
			}
		}

	},

	//显示车辆类型列表
	typeSelection: function(e){
		var that = this;
		setTimeout(function(){
			that.setData({
				isCanScroll:false,
				showViewList: true,
				isShowFootNav: false
			});
		},100)

	},

	hideSelection: function(){
		this.setData({
			isCanScroll:true,
			showViewList: false,
      isShowFootNav: true
		});
	},

	//选择车辆类型列表
	showViewList: function(e){
		this.setData({
      isCanScroll:true,
			showViewList: false,
			typeStyle: "",
			typeSelectionText: e.target.dataset.name,
			typeSelectionCode: e.target.dataset.code,
			isShowFootNav: true
		});
	},
	//选择城市取消按钮
	cancelAddressTap:function (e) {
		this.setData({
			isAddressShow: false,
			isShowFootNav: true
		});
	},
	//选择城市确定按钮
	confirmAddressTap:function (e) {
        var current_value = this.data.value;
        var provinceName = this.data.proviceData[current_value[0]].name;
        var cityName = this.data.cityData[current_value[1]].name;
        var countyName = "";
        if(this.data.districtData[current_value[2]].name!=null){
            countyName = this.data.districtData[current_value[2]].name;
        }
        this.setData({
            isShowFootNav:true,
            isAddressShow: false,
            areaStyle:"color:#1a1a1a;font-size:34rpx",
            area:provinceName+cityName+countyName,
            "address.provinceId":this.data.proviceData[current_value[0]].id,
            "address.cityId":this.data.cityData[current_value[1]].id,
            "address.countyId":this.data.districtData[current_value[2]].id,
            "address.provinceName":provinceName,
            "address.cityName":cityName,
            "address.countyName":countyName
        });
	},
	//省市区滑动事件
	bindAddressChange: function (e) {
		app.bindAddressChange(e);
	}

});
